#!/usr/bin/env python3
"""
switcheroo-control MCP Server

面向 switcheroo-control 软件的 MCP 服务器，提供对 switcheroo-control 服务管理的命令行操作封装。

MCP tools 列表：
- switcheroo_control_service_restart: 重启 switcheroo-control 服务并检查状态
  参数：无
  返回：包含命令执行结果的统一 JSON 结构
"""

from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json

mcp = FastMCP("switcheroo-control MCP Server")

@mcp.tool()
def switcheroo_control_service_restart() -> dict:
    """
    重启 switcheroo-control 服务并检查状态
    
    用途：测试 switcheroo-control 服务的重启功能，通过 systemctl 命令执行重启操作并验证服务状态
    
    返回 JSON 结构：
    {
        "success": bool,      # 操作是否成功
        "command": str,       # 执行的完整命令
        "exit_code": int,     # 命令退出码
        "stdout": str,        # 标准输出内容
        "stderr": str         # 标准错误内容
    }
    """
    try:
        # 重启服务
        restart_cmd = ["systemctl", "restart", "switcheroo-control.service"]
        restart_result = subprocess.run(restart_cmd, capture_output=True, text=True, timeout=30)
        
        # 检查服务状态
        status_cmd = ["systemctl", "status", "switcheroo-control.service"]
        status_result = subprocess.run(status_cmd, capture_output=True, text=True, timeout=30)
        
        # 组合结果
        success = restart_result.returncode == 0 and status_result.returncode == 0
        
        return {
            "success": success,
            "command": f"{' '.join(restart_cmd)} && {' '.join(status_cmd)}",
            "exit_code": restart_result.returncode if restart_result.returncode != 0 else status_result.returncode,
            "stdout": f"Restart output: {restart_result.stdout}\nStatus output: {status_result.stdout}",
            "stderr": f"Restart error: {restart_result.stderr}\nStatus error: {status_result.stderr}"
        }
        
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": "systemctl restart switcheroo-control.service && systemctl status switcheroo-control.service",
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command execution timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": "systemctl restart switcheroo-control.service && systemctl status switcheroo-control.service",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Error executing command: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()